<template>
  <div>
    <div class="header">
      <div class="search">
        <el-input v-model="searchValue" placeholder="请输入内容" clearable class="input-with-select" width @input="search">
          <el-select slot="prepend" v-model="searchSelect" placeholder="请选择" class="el-input--suffix1">
            <el-option v-for="(item, index) in optionConfig.option_name" :key="index" :value="index" :label="item" />
          </el-select>
        </el-input>
      </div>
      <div class="left_but">
        <slot />
      </div>
    </div>
  </div>
</template>

<script>
import { tableDataProcess } from '@/utils/diy_funtion'
export default {
  name: 'Header',
  props: {
    // 搜索选项配置 选项名称要与对象名称顺序 一致
    optionConfig: {
      // 选项名称
      option_name: {
        type: String,
        required: true
      },
      // 搜索对象名称
      object_name: {
        type: Array,
        required: true
      },
      type: Object,
      required: true
    },
    listData: {
      type: Array,
      required: true
    }
  },

  data() {
    return {
      searchSelect: 0,
      searchValue: ''
    }
  },

  watch: {
    // 搜索选项改变时，如果搜索值不为空进行一次搜索
    searchSelect: function() {
      if (this.searchValue) this.search()
    }
  },
  methods: {
    // 搜索
    search() {
      const object_name = this.optionConfig.object_name[this.searchSelect]
      const ListData = []
      for (const i in this.listData) {
        // 判断数据是否包含搜索值
        if (this.listData[i][object_name].toString().indexOf(this.searchValue) !== -1) {
          ListData.push(this.listData[i])
        }
      }
      // 对搜索结果分页
      const { newListData } = tableDataProcess(ListData, 10)
      // 用事件change向自定义组件发送数据
      this.$emit('change', { data: newListData, total: ListData.length, searchSelect: this.searchSelect })
    }
  }
}
</script>
<style scoped>
.header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.search{
  margin: 1vh 0 ;
}
.left_but {
  flex-wrap: wrap;
  display: flex;
  margin: 1vh 0 ;
}
</style>
